/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sgsmcan.Dao;

import com.sgsmcan.Hibernate.HibernateUtil;
import com.sgsmcan.Utils.Utilitario;
import java.io.Serializable;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;

/**
 *
 * @author user
 */
public class PaginationDao<T> implements Serializable{
    
    
    public int getTotalRows(DetachedCriteria criteria){
        Session session = null;
        int totalRows = 0;
        try{
            session = HibernateUtil.getSessionFactory().openSession();
            
            criteria.setProjection(Projections.rowCount());
            totalRows = ((Integer)(criteria.getExecutableCriteria(session).uniqueResult())).intValue();
        }catch(Exception e){
            Utilitario.LOG.error("[getTotalRows]", e);
        }finally{
            if(session != null){
                session.close();
            }
        }
        return totalRows;       
    }
    
    public List<T> getList(DetachedCriteria criteria, int firstResult , int pageSize){
        Session session = null;
        List<T> auxiliar = null;
        try{
            session = HibernateUtil.getSessionFactory().openSession();
            auxiliar = criteria.getExecutableCriteria(session).setFirstResult(firstResult).setMaxResults(pageSize).list();
        }catch(Exception e){
            Utilitario.LOG.error("[getList]", e);
        }finally{
            if(session != null){
                session.close();
            }
        }      
        return auxiliar;
    }
    
    public List<T> getAllList(DetachedCriteria criteria){
        Session session = null;
        List<T> auxiliar = null;
        try{
            session = HibernateUtil.getSessionFactory().openSession();
            auxiliar = criteria.getExecutableCriteria(session).list();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(session != null){
                session.close();
            }
        }      
        return auxiliar;
    }
    
}
